/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package diet.XMLUtils;

import diet.dto.DietDTO;
import diet.dto.DishDTO;
import diet.dto.DishDetailDTO;
import diet.dto.FoodDTO;
import diet.utils.ConvertVietNamese;
import java.io.File;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.events.Characters;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 *
 * @author Vrety
 */
public class XMLUltis {

    //Search Dish using Stax
    //Search By Name
    public List<DishDTO> searchDish(String webPath, String name) {
        XMLInputFactory xif = null;
        InputStream is = null;
        XMLStreamReader reader = null;
        String filePath = webPath + "xml/Dishes.xml";
        ArrayList<DishDTO> dishes = new ArrayList<DishDTO>();
        try {
            xif = XMLInputFactory.newFactory();
            is = new FileInputStream(filePath);
            reader = xif.createXMLStreamReader(is);
            int cursorType = -1;
            while (reader.hasNext()) {
                cursorType = reader.next();
                if (cursorType == XMLStreamConstants.START_ELEMENT) {
                    String tagName = reader.getLocalName();
                    if (tagName.equals("dishID")) {
                        DishDTO dish = new DishDTO();
                        reader.next(); // character of dishID
                        dish.setDishID(Integer.parseInt(reader.getText().trim())); // get dishID
                        reader.next(); // end - dishID

                        reader.nextTag(); //start Dishname
                        tagName = reader.getLocalName();
                        reader.next(); // character of DishName
                        String Dishname = reader.getText().trim(); // get DishName text
                        if (Dishname.contains(name)) {
                            dish.setDishName(Dishname);
                            reader.next(); // end - dishName

                            reader.nextTag(); // start - dishTypeId
                            reader.next(); //character of dishTypeId
                            dish.setDishTypeId(Integer.parseInt(reader.getText().trim()));
                            reader.next(); // end - dishTypeId


                            reader.nextTag(); // start - calories
                            reader.next(); //character of calories
                            dish.setCalories(Integer.parseInt(reader.getText().trim()));
                            reader.next(); // end - calories

                            reader.nextTag(); // start - imageURL
                            reader.next(); //character of imageURL
                            dish.setImageURL(reader.getText().trim());
                            reader.next(); // end - imageURL


                            reader.nextTag(); // start - time
                            reader.next(); //character of time
                            dish.setTime(reader.getText().trim());
                            reader.next(); // end - time
                            dishes.add(dish);
                        }
                    }
                }
            }
            if (!dishes.isEmpty()) {
                return dishes;
            } else {
                return null;
            }

        } catch (XMLStreamException ex) {
            Logger.getLogger(XMLUltis.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        } catch (FileNotFoundException ex) {
            Logger.getLogger(XMLUltis.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }

    //Search Dish using Stax
    //Search By dishID
    public List<DishDTO> searchDish(String webPath, int dishID) {
        XMLInputFactory xif = null;
        InputStream is = null;
        XMLStreamReader reader = null;
        String filePath = webPath + "xml/Dishes.xml";
        ArrayList<DishDTO> dishes = new ArrayList<DishDTO>();
        try {
            xif = XMLInputFactory.newFactory();
            is = new FileInputStream(filePath);
            reader = xif.createXMLStreamReader(is);
            int cursorType = -1;
            while (reader.hasNext()) {
                cursorType = reader.next();
                if (cursorType == XMLStreamConstants.START_ELEMENT) {
                    String tagName = reader.getLocalName();
                    if (tagName.equals("dishID")) {
                        DishDTO dish = new DishDTO();
                        reader.next(); // character of dishID
                        if (dishID == Integer.parseInt(reader.getText())) {
                            dish.setDishID(dishID); // get dishID
                            reader.next(); // end - dishID

                            reader.nextTag(); //start Dishname
                            tagName = reader.getLocalName();
                            reader.next(); // character of DishName
                            dish.setDishName(reader.getText().trim());
                            reader.next(); // end - dishName

                            reader.nextTag(); // start - dishTypeId
                            reader.next(); //character of dishTypeId
                            dish.setDishTypeId(Integer.parseInt(reader.getText().trim()));
                            reader.next(); // end - dishTypeId


                            reader.nextTag(); // start - calories
                            reader.next(); //character of calories
                            dish.setCalories(Integer.parseInt(reader.getText().trim()));
                            reader.next(); // end - calories

                            reader.nextTag(); // start - imageURL
                            reader.next(); //character of imageURL
                            dish.setImageURL(reader.getText().trim());
                            reader.next(); // end - imageURL


                            reader.nextTag(); // start - time
                            reader.next(); //character of time
                            dish.setTime(reader.getText().trim());
                            reader.next(); // end - time

                            reader.nextTag(); // start - countView
                            reader.next(); //character of countView
                            dish.setCountView(Integer.parseInt(reader.getText().trim()));
                            reader.next(); // end - countView

                            reader.nextTag(); // start - cooking
                            reader.next(); //character of cooking
                            dish.setCooking(reader.getText().trim());
                            reader.next(); // end - cooking

                            reader.nextTag(); // start - userID
                            reader.next(); //character of userID
                            dish.setUserID(Integer.parseInt(reader.getText().trim()));
                            reader.next(); // end - userID

                            reader.nextTag(); // start - status
                            reader.next(); //character of status
                            dish.setStatus(reader.getText().trim());
                            reader.next(); // end - status
                            dishes.add(dish);
                        }
                    }
                }
            }
            if (!dishes.isEmpty()) {
                return dishes;
            } else {
                return null;
            }

        } catch (XMLStreamException ex) {
            Logger.getLogger(XMLUltis.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        } catch (FileNotFoundException ex) {
            Logger.getLogger(XMLUltis.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }
//Search Food using Stax

    public ArrayList<FoodDTO> searchFood(String webPath, String name) {
        XMLInputFactory xif = null;
        InputStream is = null;
        XMLStreamReader reader = null;
        String filePath = webPath + "xml/Foods.xml";
        ArrayList<FoodDTO> foods = new ArrayList<FoodDTO>();
        ConvertVietNamese cv = new ConvertVietNamese();
        try {
            xif = XMLInputFactory.newFactory();
            is = new FileInputStream(filePath);
            reader = xif.createXMLStreamReader(is);
            int cursorType = -1;
            while (reader.hasNext()) {
                cursorType = reader.next();
                if (cursorType == XMLStreamConstants.START_ELEMENT) {
                    String tagName = reader.getLocalName();
                    if (tagName.equals("foodID")) {
                        FoodDTO food = new FoodDTO();
                        reader.next(); // character of foodID
                        food.setFoodID(Integer.parseInt(reader.getText().trim())); // get foodID
                        reader.next(); // end - foodID
                        reader.nextTag(); //start CategoryID
                        reader.next(); // character of CategoryID
                        food.setCategoryID(Integer.parseInt(reader.getText().trim())); // get Category ID
                        reader.next(); // end - categoryID
                        reader.nextTag(); //start FoodName
                        tagName = reader.getLocalName();
                        reader.next(); // character of FoodName
                        String Foodname = reader.getText().trim(); // get FoodName text

                        if (cv.toStringNoAccent(Foodname.toLowerCase()).contains(name)) {
                            food.setFoodName(Foodname);
                            reader.next(); // end - FoodName
                            reader.nextTag(); // start ImageURL
                            reader.next(); //character of imageURL
                            food.setImageURL(reader.getText().trim());
                            reader.next(); // end - imageURL
                            reader.nextTag(); // start - calories
                            reader.next(); //character of calories
                            food.setCalorie(Integer.parseInt(reader.getText().trim()));
                            reader.next(); // end - calories
                            reader.nextTag(); // start -carb
                            reader.next();//character of carb
                            food.setCarb(Float.parseFloat(reader.getText().trim()));
                            reader.next(); //end - carb
                            reader.nextTag(); // start -protein
                            reader.next();//character of protein
                            food.setProtein(Float.parseFloat(reader.getText().trim()));
                            reader.next(); //end - protein
                            reader.nextTag(); // start -fat
                            reader.next();//character of fat
                            food.setFat(Float.parseFloat(reader.getText().trim()));
                            reader.next(); //end - fat
                            reader.nextTag(); // start -Amount
                            reader.next();//character of amount
                            food.setAmount(reader.getText().trim());
                            reader.next(); //end -amount
                            foods.add(food);
                        }
                    }
                }
            }
            if (!foods.isEmpty()) {
                return foods;
            } else {
                return null;
            }

        } catch (XMLStreamException ex) {
            Logger.getLogger(XMLUltis.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        } catch (FileNotFoundException ex) {
            Logger.getLogger(XMLUltis.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }

    public ArrayList<DietDTO> searchDiet(String webPath, String name) {
        XMLInputFactory xif = null;
        InputStream is = null;
        XMLStreamReader reader = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String filePath = webPath + "xml/Diets.xml";
        ArrayList<DietDTO> diets = new ArrayList<DietDTO>();
        try {
            xif = XMLInputFactory.newFactory();
            is = new FileInputStream(filePath);
            reader = xif.createXMLStreamReader(is);
            int cursorType = -1;
            while (reader.hasNext()) {
                cursorType = reader.next();
                if (cursorType == XMLStreamConstants.START_ELEMENT) {
                    String tagName = reader.getLocalName();
                    if (tagName.equals("dietID")) {
                        DietDTO diet = new DietDTO();
                        reader.next(); // character of dietID
                        diet.setDietID(Integer.parseInt(reader.getText().trim())); // get dietID
                        reader.next(); // end - dietID
                        reader.nextTag(); //start CategoryID
                        reader.next(); // character of CategoryID
                        diet.setCustomerID(Integer.parseInt(reader.getText().trim())); // get Customer ID
                        reader.next(); // end - CustomerID
                        reader.nextTag(); //start DatetimeBegin
                        reader.next(); // character of DatetimeBegin
                        diet.setDateTimeBegin(sdf.parse(reader.getText().trim())); // get DateTImeBegin
                        reader.next(); // end - DateTimBegin
                        reader.nextTag(); //start DateTimeEnd
                        reader.next(); // character of DateTime End
                        diet.setDateTimeEnd(sdf.parse(reader.getText().trim())); // get DateTimeEnd
                        reader.next(); // end DateTime End
                        reader.nextTag(); // start DietName
                        tagName = reader.getLocalName();
                        reader.next(); // character of DietName
                        String Dietname = reader.getText().trim(); // get Dietname text
                        if (Dietname.contains(name)) {
                            diet.setDietName(Dietname);
                            reader.next(); // end - DietName
                            reader.nextTag(); // start Calories need
                            reader.next(); //character of Calories need
                            diet.setCalorieNeed(Integer.parseInt(reader.getText().trim()));
                            reader.next(); // end - Calories need
                            reader.nextTag(); // start - isNew
                            reader.next(); //character of isNew
                            diet.setIsNew(Integer.parseInt(reader.getText().trim()));
                            reader.next(); //end - isNew
                            diets.add(diet);
                        }
                    }
                }
            }
            if (!diets.isEmpty()) {
                return diets;
            } else {
                return null;
            }

        } catch (ParseException ex) {
            Logger.getLogger(XMLUltis.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        } catch (XMLStreamException ex) {
            Logger.getLogger(XMLUltis.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        } catch (FileNotFoundException ex) {
            Logger.getLogger(XMLUltis.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }

    //Search Dish by Food using Stax
    public List<DishDTO> searchDish(String webPath, List<FoodDTO> foodEssential, List<FoodDTO> foodNoEssential) {
        XMLInputFactory xif = null;
        InputStream is = null;
        XMLStreamReader reader = null;
        String filePath = webPath + "xml/DishDetails.xml";
        ArrayList<DishDTO> dishes = new ArrayList<DishDTO>();
        try {
            if (foodEssential.isEmpty() && foodNoEssential.isEmpty()) {
                return null;
            }
            xif = XMLInputFactory.newFactory();
            is = new FileInputStream(filePath);
            reader = xif.createXMLStreamReader(is);
            int cursorType = -1;
            while (reader.hasNext()) {
                cursorType = reader.next();
                if (cursorType == XMLStreamConstants.START_ELEMENT) {
                    String tagName = reader.getLocalName();
                    if (tagName.equals("foodID")) {
                        boolean isFound = false;
                        reader.next(); // character of foodID
                        int foodID = Integer.parseInt(reader.getText());
                        //Get all dish that have match foodEssential
                        for (int i = 0; i < foodEssential.size(); i++) {

                            if (foodID == foodEssential.get(i).getFoodID()) {
                                DishDTO dish = new DishDTO();
                                reader.next(); // end - foodID

                                reader.nextTag(); //start dishID
                                reader.next(); // character of dishID
                                //Check for duplicate dish
                                boolean isDuplication = false;
                                for (Iterator<DishDTO> it = dishes.iterator(); it.hasNext();) {
                                    DishDTO dishDTO = it.next();

                                    if (dishDTO.getDishID() == Integer.parseInt(reader.getText())) {
                                        isDuplication = true;
                                        break;
                                    }
                                }
                                if (isDuplication) {
                                    break;
                                }
                                dish.setDishID(Integer.parseInt(reader.getText()));
                                reader.next(); // end - dishID

                                reader.nextTag(); //start dishName
                                reader.next(); // character of dishName
                                dish.setDishName((reader.getText()));
                                reader.next(); // end - dishName

                                reader.nextTag(); //start ImageURL
                                reader.next(); // character of ImageURL
                                dish.setImageURL((reader.getText()));
                                reader.next(); // end - ImageURL

                                reader.nextTag(); //start calories
                                reader.next(); // character of calories
                                dish.setCalories((Integer.parseInt(reader.getText())));
                                reader.next(); // end - calories

                                dishes.add(dish);
                                isFound = true;

                            }
                        }
                        if (!isFound) {
                            //Get all dish that have match foodNoEssential
                            for (int i = 0; i < foodNoEssential.size(); i++) {
                                if (foodID == foodNoEssential.get(i).getFoodID()) {
                                    DishDTO dish = new DishDTO();
                                    reader.next(); // end - foodID

                                    reader.nextTag(); //start dishID
                                    reader.next(); // character of dishID
                                    dish.setDishID(Integer.parseInt(reader.getText()));
                                    //Check for duplicate dish
                                    boolean isDuplication = false;
                                    for (Iterator<DishDTO> it = dishes.iterator(); it.hasNext();) {
                                        DishDTO dishDTO = it.next();

                                        if (dishDTO.getDishID() == Integer.parseInt(reader.getText())) {
                                            isDuplication = true;
                                            break;
                                        }
                                    }
                                    if (isDuplication) {
                                        break;
                                    }
                                    reader.next(); // end - dishID

                                    reader.nextTag(); //start dishName
                                    reader.next(); // character of dishName
                                    dish.setDishName((reader.getText()));
                                    reader.next(); // end - dishName

                                    reader.nextTag(); //start ImageURL
                                    reader.next(); // character of ImageURL
                                    dish.setImageURL((reader.getText()));
                                    reader.next(); // end - ImageURL

                                    reader.nextTag(); //start calories
                                    reader.next(); // character of calories
                                    dish.setCalories((Integer.parseInt(reader.getText())));
                                    reader.next(); // end - calories

                                    dishes.add(dish);
                                }
                            }
                        }
                    }
                }
            }
            if (!dishes.isEmpty()) {
                return dishes;
            } else {
                return null;
            }

        } catch (XMLStreamException ex) {
            Logger.getLogger(XMLUltis.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        } catch (FileNotFoundException ex) {
            Logger.getLogger(XMLUltis.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }

    //Search Dish by Food using Stax
    // Using Iterator
    public List<DishDTO> getAlphaListIter(String webPath, List<DishDTO> simpleList, List<FoodDTO> foodEssential) {
        //InputStream is = null;
        //XMLStreamReader reader = null;
        String filePath = webPath + "xml/DishDetails.xml";
        ArrayList<DishDTO> dishes = new ArrayList<DishDTO>();
        //count to find enough condition for betaList
        int countFound = 0;
        int needFound = foodEssential.size();

        boolean foundDishID = false;

        try {
            if (foodEssential.isEmpty()) {
                return null;
            }
            XMLInputFactory xif = XMLInputFactory.newFactory();
            FileReader fileReader = new FileReader(filePath);
            XMLEventReader xer = xif.createXMLEventReader(fileReader);

            List<DishDTO> aplhaList = new ArrayList<DishDTO>();
            //is = new FileInputStream(filePath);
            //reader = xif.createXMLStreamReader(is);
            for (Iterator<DishDTO> it = simpleList.iterator(); it.hasNext();) {
                //search dishID
                DishDTO dishDTO = it.next();

                while (xer.hasNext()) {
                    XMLEvent event = xer.nextEvent();
                    if (event.isStartElement()) {
                        StartElement start = event.asStartElement();
                        if (start.getName().getLocalPart().equals("dishID")) {
                            event = xer.nextEvent();
                            if (event.asCharacters().getData().equals("" + dishDTO.getDishID())) {
                                foundDishID = true;
                            }
                        }
                    }
                }
            }

            if (!aplhaList.isEmpty()) {
                return aplhaList;
            } else {
                return null;
            }

        } catch (XMLStreamException ex) {
            Logger.getLogger(XMLUltis.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        } catch (FileNotFoundException ex) {
            Logger.getLogger(XMLUltis.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }

    public List<DishDTO> getAlphaList(String webPath, List<DishDTO> simpleList, List<FoodDTO> foodEssential) {
        XMLInputFactory xif = null;
        InputStream is = null;
        XMLStreamReader reader = null;
        String filePath = webPath + "xml/DishDetails.xml";
        ArrayList<DishDTO> dishes = new ArrayList<DishDTO>();
        //count to find enough condition for betaList
        int countFound = 0;
        int needFound = foodEssential.size();

        boolean foundDishID = false;
        List<DishDTO> alphaList = new ArrayList<DishDTO>();

        try {
            if (foodEssential.isEmpty()) {
                return null;
            }
            for (Iterator<DishDTO> it = simpleList.iterator(); it.hasNext();) {
                DishDTO dishDTO = it.next();


                xif = XMLInputFactory.newFactory();
                is = new FileInputStream(filePath);
                reader = xif.createXMLStreamReader(is);
                int cursorType = -1;
                while (reader.hasNext()) {
                    cursorType = reader.next();
                    if (cursorType == XMLStreamConstants.START_ELEMENT) {
                        String tagName = reader.getLocalName();
                        if (tagName.equals("foodID")) {
                            reader.next(); // character of foodID
                            int foodID = Integer.parseInt(reader.getText());
                            reader.next(); // end of foodID

                            reader.nextTag(); //start dishID
                            reader.next(); // character of dishID
                            int dishID = Integer.parseInt(reader.getText());
                            if (dishID == dishDTO.getDishID()) {
                                for (Iterator<FoodDTO> it1 = foodEssential.iterator(); it1.hasNext();) {
                                    FoodDTO food = it1.next();
                                    if (food.getFoodID() == foodID) {
                                        countFound++;
                                    }

                                }
                            }

                        }
                    }
                    if (countFound >= needFound) {
                        alphaList.add(dishDTO);
                        break;
                    }
                }
            }
            if (!alphaList.isEmpty()) {
                return alphaList;
            } else {
                return null;
            }
        } catch (XMLStreamException ex) {
            Logger.getLogger(XMLUltis.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        } catch (FileNotFoundException ex) {
            Logger.getLogger(XMLUltis.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }

    //Search Dish by Food using Stax
    //
    public List<DishDetailDTO> searchDishDetail(String webPath, int dishID) {
        XMLInputFactory xif = null;
        InputStream is = null;
        XMLStreamReader reader = null;
        String filePath = webPath + "xml/DishDetails.xml";
        List<DishDetailDTO> dishdetails = new ArrayList<DishDetailDTO>();
        try {

            xif = XMLInputFactory.newFactory();
            is = new FileInputStream(filePath);
            reader = xif.createXMLStreamReader(is);
            int cursorType = -1;
            while (reader.hasNext()) {
                cursorType = reader.next();
                if (cursorType == XMLStreamConstants.START_ELEMENT) {
                    String tagName = reader.getLocalName();
                    if (tagName.equals("foodID")) {
                        DishDetailDTO dishdetail = new DishDetailDTO();
                        reader.next(); // character of foodID
                        dishdetail.setFoodID(Integer.parseInt(reader.getText().trim())); // get foodID
                        reader.next(); // end - foodID

                        reader.nextTag(); //start dishID
                        reader.next(); // character of dishID
                        if (dishID == Integer.parseInt(reader.getText().trim())) {
                            dishdetail.setDishID(dishID); // get dishID
                            reader.next(); // end - dishID

                            reader.nextTag(); //start dishName
                            reader.next(); // character of dishName
                            dishdetail.setDishName((reader.getText().trim())); // get dishName
                            reader.next(); // end - dishName

                            reader.nextTag(); //start imageURL
                            reader.next(); // character of imageURL
                            dishdetail.setImageURL((reader.getText().trim())); // get imageURL
                            reader.next(); // end - imageURL

                            reader.nextTag(); //start calories
                            reader.next(); // character of calories
                            dishdetail.setCalories((Integer.parseInt(reader.getText().trim()))); // get calories
                            reader.next(); // end - calories

                            reader.nextTag(); //start ammount
                            reader.next(); // character of ammount
                            dishdetail.setAmmount(Float.parseFloat(reader.getText().trim())); // get ammount
                            reader.next(); // end - ammount

                            reader.nextTag(); //start essential
                            reader.next(); // character of essential
                            dishdetail.setEssential((Boolean.parseBoolean(reader.getText().trim()))); // get essential
                            reader.next(); // end - essential

                            reader.nextTag(); //start foodName
                            reader.next(); // character of foodName
                            dishdetail.setFoodName((reader.getText().trim())); // get foodName
                            reader.next(); // end - foodName


                            reader.nextTag(); //start dishDetailID
                            reader.next(); // character of dishDetailID
                            dishdetail.setDishDetailID(Integer.parseInt(reader.getText().trim())); // get dishDetailID
                            reader.next(); // end - dishDetailID

                            dishdetails.add(dishdetail);
                        }

                    }
                }
            }
            if (!dishdetails.isEmpty()) {
                return dishdetails;
            } else {
                return null;
            }

        } catch (XMLStreamException ex) {
            Logger.getLogger(XMLUltis.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        } catch (FileNotFoundException ex) {
            Logger.getLogger(XMLUltis.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }

    //Create FO file
    public static void createFOFile(String xslPath, String xmlPath, String output) {
        {
            try {
                TransformerFactory tfactory = TransformerFactory.newInstance();
                Transformer transformer = tfactory.newTransformer(new StreamSource(xslPath));
//                FileOutputStream fo = new FileOutputStream(output);
//                osw = new OutputStreamWriter(fo, "UTF-8");
//                StreamResult result = new StreamResult(osw);
                transformer.transform(new StreamSource(xmlPath), new StreamResult(new FileOutputStream(output)));
            } catch (TransformerException ex) {
                Logger.getLogger(XMLUltis.class.getName()).log(Level.SEVERE, null, ex);
            } catch (FileNotFoundException ex) {
                Logger.getLogger(XMLUltis.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
    }
    //Test Create FO and PDF file.

    public static boolean test(String realPath) {
        String xslPath = realPath + "xml/DishesFO.xsl";
        String xmlPath = realPath + "xml/Dishes.xml";
        String output = realPath + "xml/Dishes.fo";
//        String xslPath = realPath + "xml/DietsFO.xsl";
//        String xmlPath = realPath + "xml/Diets.xml";
//        String output = realPath + "xml/Diets.fo";
        XMLUltis.createFOFile(xslPath, xmlPath, output);
//        File xmlFile = new File(realPath + "xml/Diets.fo");
//        File pdfFile = new File(realPath + "xml/Diets.pdf");
        File xmlFile = new File(realPath + "xml/Dishes.fo");
        File pdfFile = new File(realPath + "xml/Dishes.pdf");
        return PDFGenerating.CreatePDF(xmlFile, pdfFile, realPath);

    }

    public static boolean createDishesPDF(String realPath) {
        String xslPath = realPath + "xml/DishesFO.xsl";
        String xmlPath = realPath + "xml/Dishes.xml";
        String output = realPath + "xml/Dishes.fo";

        XMLUltis.createFOFile(xslPath, xmlPath, output);

        File xmlFile = new File(realPath + "xml/Dishes.fo");
        File pdfFile = new File(realPath + "xml/Dishes.pdf");
        return PDFGenerating.CreatePDF(xmlFile, pdfFile, realPath);

    }
    public static boolean createFoodsPDF(String realPath) {
        String xslPath = realPath + "xml/FoodsFO.xsl";
        String xmlPath = realPath + "xml/Foods.xml";
        String output = realPath + "xml/Foods.fo";

        XMLUltis.createFOFile(xslPath, xmlPath, output);

        File xmlFile = new File(realPath + "xml/Foods.fo");
        File pdfFile = new File(realPath + "xml/Foods.pdf");
        return PDFGenerating.CreatePDF(xmlFile, pdfFile, realPath);

    }

    //Modify xml by using DOM
    //NhuNHU
    public void deleteDietDetailXMLFile(String filepath, int dietDetailID) {
        int count = 0;
        try {
            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            Document doc = docBuilder.parse(filepath);

            Element root = doc.getDocumentElement();
            NodeList nList = doc.getElementsByTagName("dietInfo");

            for (int i = 0; i < nList.getLength(); i++) {
                Node dietInfos = nList.item(i);
                NodeList dietInfoChilds = dietInfos.getChildNodes();
                for (int j = 0; j < dietInfoChilds.getLength(); j++) {
                    Node child = dietInfoChilds.item(j);
                    if ("dietDetailID".equals(child.getNodeName())) {
                        if (Integer.parseInt(child.getTextContent()) == dietDetailID) {
                            root.removeChild(dietInfos);
                            break;
                        }
                    }
                }
            }

            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer trans = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(new File(filepath));
            trans.transform(source, result);

        } catch (TransformerException ex) {
            Logger.getLogger(XMLUltis.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SAXException ex) {
            Logger.getLogger(XMLUltis.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(XMLUltis.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(XMLUltis.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static String getStringAutoComplete(String filepath) {
        try {
            String result = "";
            boolean bFound = false;
            FileInputStream inputFile = null;
            XMLInputFactory xif = XMLInputFactory.newInstance();
            File file = new File(filepath);
            inputFile = new FileInputStream(file);
            XMLStreamReader reader = xif.createXMLStreamReader(inputFile);
            while (reader.hasNext()) {
                int eventType = reader.getEventType();
                switch (eventType) {
                    case XMLStreamConstants.START_ELEMENT:
                        if (reader.getLocalName().equals("Name")) {
                            bFound = true;
                        }
                        break;
                    case XMLStreamConstants.CHARACTERS:
                        if (bFound) {
                            if (result.equals("")) {//first text
                                result += reader.getText();
                            } else {
                                result = result + "," + reader.getText();
                            }
                            bFound = false; //reset
                        }
                        break;
                }
                reader.next();
            }
            int eventType = reader.getEventType();
            if (eventType == XMLStreamConstants.END_DOCUMENT) {
                System.out.print("END document!");
                reader.close();
            }
            return result;
        } catch (XMLStreamException ex) {
            Logger.getLogger(XMLUltis.class.getName()).log(Level.SEVERE, null, ex);
            return "";
        } catch (FileNotFoundException ex) {
            Logger.getLogger(XMLUltis.class.getName()).log(Level.SEVERE, null, ex);
            return "";
        }
    }
}
